#!/usr/bin/python
# coding: utf8
f = open("dependency.py")
fs = f.readlines()
f.close()
f = fs
del fs
depDir = {}
depIndir = {}
curFile = ""
for line in f:
#	print "LINE:", line
	if line == "\n":
#		print "EMPTYLINE"
		continue
	elif line[0] == "\t":
		depDir[curFile] += [line[1:-1]]
	else:
		curFile = line[:-2]
		depDir[curFile] = []
#		print "NEW FILE:", curFile
#	print depDir
#	print
print depDir

checking = []
def check(key):
	global depDir
	global depIndir
	global checking
	if key in depIndir:
		return
#	print "Checking", key
	if key in checking:
		print 'DEAD LOCK! File', key, 'checked twice!'
		print 'Circle:', checking
		assert(1 == 0)
	checking += [key]
	value = depDir[key]
	dep = []
	assert(len(value) > 0)
	for father in value:
		if father == "pass":
			break
		else:
			dep += [father]
			check(father)
			dep += depIndir[father]
#	print "Checked", key
	dep.sort()
	dep_ = []
	for i in range(len(dep)):
		if i == 0 or dep[i] != dep[i - 1]:
			dep_ += [dep[i]]
	depIndir[key] = dep_
	assert(checking.index(key) == len(checking) - 1)
	del checking[checking.index(key)]

for key in depDir.keys():
	check(key)
	print key, ":", depIndir[key]

def getName(filename):
	p = filename.rfind(".")
	return filename[:p]
def getExt(filename):
	p = filename.rfind(".")
	return filename[p+1:]

s = '''\
CXX = g++
RMFLAGS = -f -v
main: main.o Token.o TokenIntExp.o TokenBoolExp.o VarTable.o TokenSen.o TokenBlock.o TokenSenCtrl.o
	$(CXX) $^ -o $@ $(CXXFLAGS)
.PHONY: clean
clean:
	rm *.o $(RMFLAGS)
	rm *~ $(RMFLAGS)
	rm main $(RMFLAGS)
'''
for key, value in depIndir.items():
	if getExt(key) == "cpp":
		s += getName(key) + ".o: " + key
		for ancestor in value:
			s += " " + ancestor
		s += "\n"
		s += "\t$(CXX) $< -c $(CXXFLAGS)\n"
s += "\n"
f = open("Makefile", "w")
f.write(s)
f.close()

